package cyce.peer;

import java.io.*;
import java.rmi.RemoteException;

import javax.swing.*;

import cyce.common.ConfigParser;
import cyce.file.*;
import cyce.peer.filechooser.*;

/**
 * Frame to contain the FileChooser panel
 */
public class PeerUI extends JFrame {

	private static final long serialVersionUID = -6572560447546290434L;

	public PeerUI(Peer peer) {
		super("CYCE Distributed File System Client");
		
		
		FileModel model = new FileModel(peer);
		FileChooser chooser = new FileChooser(model);
		
		this.getContentPane().add(chooser);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.pack();
	}
	
	/**
	 * Main method for Peer
	 * read in file structure from local list, load up a PeerUI instance
	 */
	public static void main(String[] args) {
		// set the lease timeout so that when the server dies, 
		// the peer attempts to connect to another server
		System.setProperty("java.rmi.dgc.leaseValue", "10000");
		
		ConfigParser config;
		try {
			config = new ConfigParser("peerConfig.xml");
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		
		String xml = "";
		try {
			BufferedReader reader = new BufferedReader(new FileReader(config.getValue("fileXML")));
			String line = reader.readLine();
			while (line != null) {
				xml += line;
				line = reader.readLine();
			}
		}
		catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
			return;
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
			return;
		}
		
		
		
		Directory root = FileFactory.deserializeDirectory(xml);
		
		String primaryServerName = config.getValue("primaryServerName");
		int primaryServerPort = Integer.parseInt(config.getValue("primaryServerPort"));
		String secondaryServerName = config.getValue("secondaryServerName");
		int secondaryServerPort = Integer.parseInt(config.getValue("secondaryServerPort"));
		String localFileStore = config.getValue("localFileStore");
		String xmlFileStore = config.getValue("fileXML");
		
		Peer peer;
		try {
			peer = new Peer(
					primaryServerName,
					primaryServerPort,
					secondaryServerName,
					secondaryServerPort,
					localFileStore,
					xmlFileStore,
					root);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		
		PeerUI chooserTest = new PeerUI(peer);
		chooserTest.setVisible(true);
	}

}
